﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using Shinkansen.Core;
using Shinkansen.Model;
using Shinkansen.Runtime;
using Shinkansen.UI;

namespace Shinkansen.Mvc
{
    public class ImageTagBuilder : TagBuilderBase
    {
        private readonly ImageReference _image;
        private readonly Action<string> _registrationCallback;

        /// <summary>
        /// Initializes a new instance of the <see cref="ImageTagBuilder"/> class.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <param name="registrationCallback">The registration callback.</param>
        public ImageTagBuilder (ImageReference image, Action<string> registrationCallback)
        {
            _image = image;
            _registrationCallback = registrationCallback;
        }

        /// <summary>
        /// Processes the image reference.
        /// </summary>
        public override void Run ()
        {
            IQueryStringBuilder builder = 
                new QueryStringForImageBuilder (
                    new IndividualQueryStringBuilder (_image));

            EncryptedQueryString qs = new EncryptedQueryString ();
            builder.ConstructQueryString (qs);

            string tag = BuildImageTag (qs);
            _registrationCallback (tag);
        }

        /// <summary>
        /// Builds the image tag.
        /// </summary>
        /// <param name="qs">Constructed query string.</param>
        /// <returns></returns>
        private string BuildImageTag (QueryString qs)
        {
            object      htmlAttributes = _image.HtmlAttributes;
            TagBuilder  builder = new TagBuilder ("img");
            string      url = string.Format ("{0}?{1}={2}", PathToAxd, Tokens.SecureToken, qs);

            builder.MergeAttribute ("src", url);
            builder.MergeAttribute ("alt", _image.AltText);
            builder.MergeAttributes (new RouteValueDictionary (htmlAttributes));

            // Render tag
            return builder.ToString (TagRenderMode.SelfClosing);
        }
    }
}